<script setup>
import { ArrowLeftIcon } from 'tdesign-icons-vue-next'
import { useRoute, useRouter } from 'vue-router'
import { ref, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { addMonthlyCard, editMonthlyCard, getMonthlyCard, renewMonthlyCard } from '@/api/monthly'
import MainContent from '@/components/Main-Content.vue'

const router = useRouter()
const route = useRoute()
const pageTitleMap = {
    'renew': '月卡续费',
    'edit': '月卡修改',
    'add': '月卡新增'
}
const formInstance = ref(null)
const today = ref(new Date().toLocaleString().split(' ')[0].replaceAll('/', '-'))
const disableDate = computed(() => ({ before: today.value }))
const checkedDate = ref([today.value])
const rules = ref({
    personName: [
        { required: true, message: '请输入车主姓名', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ],
    phoneNumber: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur' }
    ],
    carNumber: [
        { required: true, message: '请输入车牌号码', trigger: 'blur' },
        {
            pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
            message: '车牌号码格式有误',
            trigger: 'blur'
        }
    ],
    carBrand: [
        { required: true, message: '请输入车辆品牌', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ],
    cardEndDate: [
        { required: true, message: '请选择有效期', trigger: 'blur' }
    ],
    paymentMethod: [
        { required: true, message: '请选择支付方式', trigger: 'blur' }
    ],
    paymentAmount: [
        { required: true, message: '请输入支付金额', trigger: 'blur' }
    ]
})
const form = ref({})
const disabledList = ref({})

const back = () => router.back()
const datePickerChange = e => {
    checkedDate.value = [today.value, e[1]]
    form.value.cardStartDate = e[0]
    form.value.cardEndDate = e[1]
}
const confirm = async () => {
    const valid = await formInstance.value.validate()
    if (typeof valid === 'object' && valid) return

    if (route.query.type === 'renew') {
        const res = await renewMonthlyCard({
            cardStartDate: form.value.cardStartDate,
            cardEndDate: form.value.cardEndDate,
            paymentAmount: form.value.paymentAmount,
            paymentMethod: form.value.paymentMethod,
            carInfoId: form.value.carInfoId
        })
        if (res.code !== 10000) return
        await MessagePlugin.success('续费成功!')
        await dateReset(form.value.cardEndDate, 'renew')
        await reset(route.query.type)
    } else if (route.query.type === 'edit') {
        delete form.value.cardStatus
        const res = await editMonthlyCard(form.value)
        if (res.code !== 10000) return
        await MessagePlugin.success('修改成功!')
        await backDisplay()
    } else {
        const res = await addMonthlyCard(form.value)
        if (res.code !== 10000) return
        await MessagePlugin.success('添加成功!')
        await reset(route.query.type)
        checkedDate.value = [today.value]
    }
}
const backDisplay = async () => {
    const res = (await getMonthlyCard(route.query.id)).data
    form.value = res
    if (route.query.type === 'renew') dateReset(res.cardEndDate, 'renew')
    if (route.query.type === 'edit') {
        checkedDate.value = [res.cardStartDate, res.cardEndDate]
        dateReset(res.cardStartDate, 'edit')
    }
}
const reset = async type => {
    if (type === 'renew') {
        checkedDate.value = [today.value]
        form.value.cardEndDate = ''
        form.value.paymentMethod = ''
        form.value.paymentAmount = ''
    } else {
        formInstance.value.reset()
    }
}
const dateReset = (str, type) => {
    let count = 0
    if (type === 'renew') count = 1
    const date = new Date(str)
    date.setDate(date.getDate() + count)
    const endDate = date.toLocaleString().split(' ')[0].replaceAll('/', '-')
    if (type === 'renew') checkedDate.value = [endDate]
    today.value = endDate
}

if (route.query.type === 'renew') {
    disabledList.value = {
        personName: true,
        phoneNumber: true,
        carNumber: true,
        carBrand: true
    };  // 分号不能删除
    (async () => {
        await backDisplay()
        await reset(route.query.type)
    })()
} else if (route.query.type === 'edit') {
    backDisplay()
}
</script>

<template>
    <main-content>
        <div class="top">
            <div class="header">
                <t-button variant="outline" @click="back">
                    <template #icon>
                        <ArrowLeftIcon/>
                    </template>
                    返回
                </t-button>
                <span class="title">{{ pageTitleMap[route.query.type] }}</span>
            </div>

            <t-divider theme="vertical"/>

            <div class="body">
                <t-form class="form" ref="formInstance" labelAlign="top"
                        :rules="rules" :data="form" :disabled="disabledList.all">
                    <div class="form-left">
                        <h3>车辆信息</h3>
                        <t-form-item label="车主姓名" name="personName">
                            <t-input placeholder="请输入车主姓名"
                                     :disabled="disabledList.personName"
                                     v-model.trim="form.personName"/>
                        </t-form-item>
                        <t-form-item label="手机号码" name="phoneNumber">
                            <t-input-number placeholder="请输入手机号码"
                                            :disabled="disabledList.phoneNumber"
                                            v-model.trim="form.phoneNumber"
                                            theme="column"/>
                        </t-form-item>
                        <t-form-item label="车牌号码" name="carNumber">
                            <t-input placeholder="请输入车牌号码"
                                     :disabled="disabledList.carNumber"
                                     v-model.trim="form.carNumber"/>
                        </t-form-item>
                        <t-form-item label="车辆品牌" name="carBrand">
                            <t-input placeholder="请输入车辆品牌"
                                     :disabled="disabledList.carBrand"
                                     v-model.trim="form.carBrand"/>
                        </t-form-item>
                    </div>

                    <div class="form-right">
                        <h3>月卡缴费信息</h3>
                        <t-form-item label="有效日期" name="cardEndDate">
                            <t-date-range-picker allow-input clearable
                                                 v-model:disableDate="disableDate"
                                                 :placeholder="['开始日期', '结束日期']"
                                                 :disabled="disabledList.checkedDate"
                                                 v-model="checkedDate"
                                                 @change="datePickerChange"/>
                        </t-form-item>
                        <t-form-item label="支付方式" name="paymentMethod">
                            <t-select
                                v-model.trim="form.paymentMethod"
                                :disabled="disabledList.paymentMethod"
                                showArrow>
                                <t-option key="Alipay" label="支付宝" value="Alipay"/>
                                <t-option key="WeChat" label="微信" value="WeChat"/>
                                <t-option key="Cash" label="现金" value="Cash"/>
                            </t-select>
                        </t-form-item>
                        <t-form-item label="支付金额" name="paymentAmount">
                            <t-input-number placeholder="请输入支付金额"
                                            :disabled="disabledList.paymentAmount"
                                            v-model.trim="form.paymentAmount"
                                            theme="column"/>
                        </t-form-item>
                    </div>
                </t-form>
            </div>
        </div>

        <div class="bottom">
            <div>
                <t-button variant="outline" @click="reset(route.query.type)">重 置</t-button>
                <t-button style="margin-left: 20px" @click="confirm">确 定</t-button>
            </div>
        </div>
    </main-content>
</template>

<style scoped lang="scss">
.header {
    display: flex;
    align-items: center;
    padding: 20px 20px 0;

    .title {
        color: var(--td-text-color-primary);
        font-size: 24px;
        font-weight: 600;
        margin-left: 30px;
    }
}

.body {
    .form {
        display: flex;
        justify-content: space-between;

        > div {
            flex: 1;
            padding: 0 60px;
        }

        .form-left {
            padding-right: 0;
        }

        .t-input-number {
            flex: 1;
        }

        .t-date-range-picker {
            width: 100%;
        }
    }
}

.bottom {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    padding-top: 20px;
}

.t-divider {
    margin: 20px 0;
}
</style>
